package com.atjava.webspider.logic;

import java.io.File;

import com.atjava.jox.io.JOXReader;
import com.atjava.jox.io.JOXWriter;
import com.atjava.webspider.consts.Const;
import com.atjava.webspider.model.AppConfig;
import com.atjava.webspider.model.DbConfig;
import com.atjava.webspider.model.SiteConfig;
import com.atjava.webspider.util.LogUtil;

public final class ConfigLogic {

	private static AppConfig appConfig;
	
	private static SiteConfig siteConfig;
	
	private static DbConfig dbConfig;
	
	private static Object readConfig(String cfgPath,Class<?> cfgCls){
		JOXReader reader = new JOXReader();
		File cfgFile = new File(cfgPath);
		try {
			Object config = reader.readXml(cfgFile, cfgCls);
			return config;
		} catch (Exception e) {
			LogUtil.info("Read config file faild! " + cfgFile.getAbsolutePath());
			e.printStackTrace();
		}
		return null;
	}
	
	private static void saveConfig(String cfgPath,Object cfgModel){
		JOXWriter writer = new JOXWriter();
		File cfgFile = new File(cfgPath);
		try {
			writer.writeXml(cfgFile, cfgModel);
		} catch (Exception e) {
			LogUtil.info("Save config file faild! " + cfgFile.getAbsolutePath());
			e.printStackTrace();
		}
	}
	
	public static AppConfig getAppConfig(){
		if(appConfig == null){
			appConfig = (AppConfig)readConfig
			(Const.APP_CONFIG_PATH,AppConfig.class);
		}
		return appConfig;
	}
	
	public static SiteConfig getSiteConfig(){
		if(siteConfig == null){
			siteConfig = (SiteConfig)readConfig
			(Const.SITE_CONFIG_PATH,SiteConfig.class);
		}
		return siteConfig;
	}

	public static DbConfig getDbConfig(){
		if(dbConfig == null){
			dbConfig = (DbConfig)readConfig
			(Const.DB_CONFIG_PATH,DbConfig.class);
		}
		return dbConfig;
	}
	
	public static void saveAppConfig(){
		saveConfig(Const.APP_CONFIG_PATH, appConfig);
	}
	
	public static void saveSiteConfig(){
		saveConfig(Const.SITE_CONFIG_PATH, siteConfig);
	}
	
	public static void saveDbConfig(){
		saveConfig(Const.DB_CONFIG_PATH, dbConfig);
	}
	
}
